export default {
    data() {
        return {
            currentTab: 'notify',
            startX: 0,
            notifications: [],
            isCenterActive: false,
            thresholds: null, // 初始化为 null,将从设置页面获取
            // 设备数据结构
            deviceData: {
                beep: 0,
                sc: 0,
                temp: 0,
                light: 0,
                humi: 0,
                air: 0,
                sp: 0,
                people: 0,
                led: 0
            },
            notificationEnabled: true, // 添加通知状态
            updateTimer: null, // 添加定时器
        }
    },
    methods: {
        // 切换标签页
        switchTab(tab) {
            this.currentTab = tab;
            switch(tab) {
                case 'home':
                    uni.redirectTo({
                        url: '/pages/index/index',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
                case 'control':
                    uni.redirectTo({
                        url: '/pages/control/control',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
                case 'setting':
                    uni.redirectTo({
                        url: '/pages/setting/setting',
                        animationType: 'pop-in',
                        animationDuration: 200
                    });
                    break;
            }
        },
        // 获取图标路径
        getTabIcon(tab) {
            const baseUrl = '../../static/';
            return this.currentTab === tab ?
                `${baseUrl}${tab}-active.png` :
                `${baseUrl}${tab}.png`;
        },

        // 处理MQTT消息
        handleMqttMessage(messageStr) {
            try {
                console.log('收到MQTT消息:', messageStr);
                const data = JSON.parse(messageStr);

                if (data && data.items) {
                    // 更新设备数据
                    Object.keys(data.items).forEach(key => {
                        if (this.deviceData.hasOwnProperty(key)) {
                            this.deviceData[key] = data.items[key].value;
                        }
                    });

                    // 检查阈值并生成通知
                    this.checkThresholds();
                }
            } catch (error) {
                console.error('处理消息失败:', error);
            }
        },

        // 检查阈值并生成通知
        checkThresholds() {
            if (!this.thresholds) return;

            // 检查温度
            if (this.deviceData.temp > this.thresholds.temperature.high) {
                this.generateNotification('温度过高', `当前温度${this.deviceData.temp}°C，建议开启空调`, '🌡️');
            } else if (this.deviceData.temp < this.thresholds.temperature.low) {
                this.generateNotification('温度过低', `当前温度${this.deviceData.temp}°C，建议关闭空调`, '🌡️');
            }

            // 检查湿度
            if (this.deviceData.humi > this.thresholds.humidity.high) {
                this.generateNotification('湿度过高', `当前湿度${this.deviceData.humi}%，建议关闭加湿器`, '💧');
            } else if (this.deviceData.humi < this.thresholds.humidity.low) {
                this.generateNotification('湿度过低', `当前湿度${this.deviceData.humi}%，建议开启加湿器`, '💧');
            }

            // 检查空气质量
            if (this.deviceData.air > this.thresholds.airQuality.high) {
                this.generateNotification('空气质量警告', `当前空气质量${this.deviceData.air}mg/m³，建议开启空气净化器`, '🌬️');
            }

            // 检查光照
            if (this.deviceData.sc > this.thresholds.light.high) {
                this.generateNotification('光照强度过高', '建议将花草移至阴凉处', '☀️');
            } else if (this.deviceData.sc < this.thresholds.light.low) {
                this.generateNotification('光照不足', '建议将花草移至光照充足处', '🌥️');
            }

            // 检查烟雾
            if (this.deviceData.sp > this.thresholds.smoke.warning) {
                this.generateNotification('烟雾警报', '检测到烟雾浓度异常，请及时检查！', '🚨');
            }
        },

        // 生成通知
        generateNotification(type, message, icon = '⚠️') {
            // 如果通知被禁用，直接返回
            if (!this.notificationEnabled) return;

            const notification = {
                icon: icon,
                title: type,
                desc: message,
                time: new Date().toLocaleTimeString(),
                offset: 0,
                read: false
            };

            let notifications = uni.getStorageSync('notifications') || [];
            notifications.unshift(notification);
            if (notifications.length > 20) {
                notifications.pop();
            }
            uni.setStorageSync('notifications', notifications);
            // 实时更新当前页面的通知列表
            this.notifications = notifications;
        },

        // 触摸开始
        touchStart(e, index) {
            this.startX = e.touches[0].clientX;
            // 重置其他项的位置
            this.notifications.forEach((item, idx) => {
                if (idx !== index) {
                    item.offset = 0;
                }
            });
        },

        // 触摸移动
        touchMove(e, index) {
            let moveX = e.touches[0].clientX - this.startX;
            let offset = Math.min(0, Math.max(-180, moveX)); // 限制滑动范围
            this.notifications[index].offset = offset;
        },

        // 触摸结束
        touchEnd(e, index) {
            let offset = this.notifications[index].offset;
            if (offset < -90) { // 如果滑动超过一半，展开操作按钮
                this.notifications[index].offset = -180;
            } else {
                this.notifications[index].offset = 0;
            }
        },

        // 加载通知数据
        loadNotifications() {
            const notifications = uni.getStorageSync('notifications') || [];
            this.notifications = notifications;
        },

        // 标记为已读
        markAsRead(index) {
            this.notifications[index].read = true;
            this.notifications[index].offset = 0;
            uni.setStorageSync('notifications', this.notifications);
            uni.showToast({
                title: '已标记为已读',
                icon: 'none'
            });
        },

        // 删除通知
        deleteNotify(index) {
            this.notifications.splice(index, 1);
            uni.setStorageSync('notifications', this.notifications);
            uni.showToast({
                title: '已删除',
                icon: 'none'
            });
        },

        // 清空所有通知
        clearAllNotifications() {
            uni.showModal({
                title: '确认清空',
                content: '是否清空所有通知？',
                success: (res) => {
                    if (res.confirm) {
                        this.notifications = [];
                        uni.setStorageSync('notifications', []);
                        uni.showToast({
                            title: '已清空所有通知',
                            icon: 'none'
                        });
                    }
                }
            });
        },

        // 处理中间按钮点击
        handleCenterClick() {
            this.isCenterActive = !this.isCenterActive;
            // 添加页面跳转
            uni.redirectTo({
                url: '/pages/deepseek/deepseek',
                animationType: 'pop-in',
                animationDuration: 200
            });
        },

        // 添加定时更新方法
        updateNotifications() {
            if(this.currentTab === 'notify') {
                const notifications = uni.getStorageSync('notifications') || [];
                this.notifications = notifications;
            }
        }
    },

    // 添加生命周期钩子
    onShow() {
        this.loadNotifications();
    },

    onLoad() {
        // 加载保存的阈值设置
        const savedThresholds = uni.getStorageSync('thresholds');
        if (savedThresholds) {
            this.thresholds = JSON.parse(savedThresholds);
        }

        this.loadNotifications();
        const app = getApp();
        app.eventBus.on('mqttMessage', this.handleMqttMessage);

        // 监听阈值更新
        uni.$on('thresholdsUpdated', () => {
            const savedThresholds = uni.getStorageSync('thresholds');
            if (savedThresholds) {
                this.thresholds = JSON.parse(savedThresholds);
            }
        });

        // 加载通知设置状态
        const notificationStatus = uni.getStorageSync('notificationEnabled');
        if (notificationStatus !== '') {
            this.notificationEnabled = notificationStatus;
        }

        // 监听通知状态变化
        uni.$on('notificationStatusChanged', (enabled) => {
            this.notificationEnabled = enabled;
        });

        // 添加定时器，每秒更新一次通知列表
        this.updateTimer = setInterval(() => {
            this.updateNotifications();
        }, 1000);
    },

    onUnload() {
        const app = getApp();
        app.eventBus.off('mqttMessage');
        uni.$off('thresholdsUpdated');
        uni.$off('notificationStatusChanged');
        // 清除定时器
        if(this.updateTimer) {
            clearInterval(this.updateTimer);
        }
    }
}